<?php

namespace app\modules\Order\models;

use Yii;

/**
 * This is the model class for table "order_assign".
 *
 * @property integer $id
 * @property integer $product_id
 * @property integer $order_id
 * @property string $name
 * @property integer $status
 * @property integer $user_id
 * @property string $created_at
 * @property string $updated_at
 */
class OrderAssign extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'order_assign';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['product_id', 'order_id', 'status', 'user_id','leader_id'], 'integer'],
            [['created_at', 'updated_at'], 'safe'],
            [['name'], 'string', 'max' => 32],
        ];
    }


    // 保存前处理
    public function beforeSave($insert) {//{{{
        if($insert){
            $this->created_at = date("Y-m-d H:i:s");
            $this->user_id    = Yii::$app->user->id;
        }
            
        return parent::beforeSave($insert);
    }//}}}

 	// 保存后执行
	public function afterSave($insert, $changedAttributes){//{{{
		parent::afterSave($insert, $changedAttributes);

		if($insert) {
			// 日志
			$desc = sprintf("创建了新分团  %s", $this->name);
			Yii::$app->logs->info($this->id, 1, $desc, '' , 2);
		}
	}//}}}




    // 获取团队 对应的订单数量
    public function getOrderCount(){
        return $this->hasMany(Order::className(), ['assign_id' => 'id'])->onCondition(['<', 'status',10])->count();
    }


    // 获取团队 对应订单的总人数
    public function getOrderPeopleCount(){
        $order = $this->hasMany(Order::className(), ['assign_id' => 'id'])->all();
		$ids = yii\helpers\ArrayHelper::map($order, 'id', 'id');
		$num = OrderRoomCustomer::find()->where(['order_id'=>$ids, 'status'=>1])->count();
		// 获取订单对应的总人数 
		return $num;
    }
    
    // 获取团队 对应的订单
    public function getOrders(){
         return $this->hasMany(Order::className(),['assign_id'=>'id']);
    }

    //获取领队信息
    public function getLeader(){
        return  $this->hasOne(Leader::className(), ['id' => 'leader_id']);
    }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'product_id' => Yii::t('app', 'Product ID'),
            'order_id' => Yii::t('app', 'Order ID'),
            'name' => Yii::t('app', 'Name'),
            'status' => Yii::t('app', 'Status'),
            'user_id' => Yii::t('app', 'User ID'),
            'created_at' => Yii::t('app', 'Created At'),
            'updated_at' => Yii::t('app', 'Updated At'),
            'leader_id' => Yii::t('app', 'Leader ID'),
        ];
    }
}
